<?php

namespace App\Models;

use App\Helpers\Parsedown;
use App\User;
use Illuminate\Database\Eloquent\Model;


class DocPage extends Model
{
    protected $guarded = [];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function children()
    {
        return $this->hasMany(DocPage::class, 'parent_id');
    }

    public function doc()
    {
        return $this->belongsTo(Doc::class, 'doc_id')->withAnyStatus();
    }

    public static function getAllPage($doc)
    {
        $all_page = $doc->pages()->get()->toArray();
        return self::sortMenu($all_page);
    }

    public function listened()
    {
        return $this->morphMany(UserListened::class, 'item');
    }

    public static function sortMenu($menus, $pid = 0, $show = ['id', 'parent_id', 'label', 'is_try', 'is_group', 'order', 'link', 'children', 'level'], $level = 1)
    {
        $arr = [];
        if (empty($menus)) {
            return [];
        }
        $i = 0;
        $web_host = config('wx.web_host');
        foreach ($menus as $value) {
            if ($value['parent_id'] == $pid) {
                $item = [
                    'id' => hashid_encode($value['id']),
                    'parent_id' => $value['parent_id'] > 0 ? hashid_encode($value['parent_id']) : 0,
                    'label' => $value['title'],
                    'is_try' => (boolean)$value['is_try'],
                    'is_group' => (boolean)$value['is_group'],
                    'order' => $value['order'],
                    'level' => $level,
                    'link' => urlencode($web_host . 'doc-page?id=' . hashid_encode($value['id'])),
                ];
                $item['children'] = self::sortMenu($menus, $value['id'], $show, $level + 1);
                if (count($item['children']) == 0) {
                    unset($item['children']);
                }
                $arr[$i] = array_only($item, $show);
                $i++;
            }
        }
        return $arr;
    }

    public static function getOrder($parent_id = 0, $doc_id)
    {
        $lastPage = self::query()->where('doc_id', $doc_id)->where('parent_id', $parent_id)->orderByDesc('order')->first(['order']);

        $order = $lastPage->order ?? 0;
        return $order + 1;

    }


    public static function getPageChildrenIds($page)
    {
        $all_page = $page->doc->pages()->get()->toArray();
        $page_list = DocPage::sortMenu($all_page, $page->id, ['id', 'children']);

        $children_ids = collect(array_flatten($page_list))->map(function ($item, $ket) {
            return hashid_decode($item);
        });

        return $children_ids;

    }

    public static function deletedByIds($user, $ids)
    {
        UserListened::query()->where('item_type', DocPage::class)->whereIn('item_id', $ids)->delete();
        return self::query()->where('user_id', $user->id)->whereIn('id', $ids)->delete();
    }


    public static function getContent($page)
    {
        $Parsedown = new Parsedown();
        $content = str_replace("\n\n```", "\n```", $page->content);
        $html = $Parsedown->setUrlsLinked(true)->text($content);

        $html = str_replace("<pre>", "<div class='scroll pre' ref='scroll'><pre>", $html);
        $html = str_replace("</pre>", "</pre></div>", $html);
        $html = str_replace("<table>", "<div class='scroll table' ref='scroll'><table>", $html);
        $html = str_replace("</table>", "</table></div>", $html);


        return $html;
    }
}
